package com.shun.interceptors

import com.fasterxml.jackson.databind.ObjectMapper
import com.shun.commons.NeedAuth
import com.shun.commons.exception.ApiException
import com.shun.commons.exception.AppException
import com.shun.entity.User
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.core.env.Environment
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.data.mongodb.core.query.Criteria
import org.springframework.data.mongodb.core.query.Query
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.stereotype.Component
import org.springframework.web.bind.annotation.SessionAttribute
import org.springframework.web.method.HandlerMethod
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * Created by Administrator on 2017/7/8.
 */
@Component
class ApiInterceptor : HandlerInterceptorAdapter() {

    @Autowired
    lateinit private var environment: Environment

    @Autowired
    lateinit private var template: MongoTemplate
    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
        if (handler is HandlerMethod) {
            handler.methodParameters.filter { it.hasParameterAnnotation(SessionAttribute::class.java) }.forEach {
                val sessionAttribute = it.getParameterAnnotation(SessionAttribute::class.java)
                if (sessionAttribute.value == "user") {
                    if (request.getHeader("X-AIO-DEBUG") != null && environment.activeProfiles.isEmpty()) {
                        val user = User()
                        user.mobile = "admin"
                        user.uuid = "61fd987d-2c1f-433a-a5d7-1638c62cc246"
                        request.session.setAttribute("user", user)
                    }
                    val user = request.session.getAttribute("user") as? User ?: throw AppException("授权无效", HttpStatus.UNAUTHORIZED)
                    val newUser = template.findOne(Query.query(Criteria("mobile").`is`(user.mobile)), User::class.java)
                    request.session.setAttribute("user", newUser)
                }
            }
        }
        return true
    }
}